<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      canvas {
        border: 1px solid #000;
        display: block;
        margin: 50px auto;
      }
    </style>
  </head>
  <body>
    <canvas id="canvas" width="600" height="600"></canvas>
    <button onclick="fn1('red')">红色</button>
    <button onclick="fn1('green')">绿色</button>
    <button onclick="fn1('black')">黑色</button>
    <button onclick="fn2()">橡皮擦</button>

    <script>
      const canvas = document.querySelector("#canvas");
      const ctx = canvas.getContext("2d");

      ctx.strokeStyle = "#000";
      ctx.lineWidth = 5;

      const fn1 = (color) => {
        ctx.strokeStyle = color;
      };

      let flag = true;

      const fn2 = () => {
        flag = false;
      };

      canvas.onmousedown = (e) => {
        if (flag) {
          ctx.beginPath();
          ctx.moveTo(e.offsetX, e.offsetY);

          canvas.onmousemove = (e) => {
            ctx.lineTo(e.offsetX, e.offsetY);
            ctx.stroke();
          };

          canvas.onmouseup = () => {
            canvas.onmousemove = null;
            ctx.closePath();
          };
        } else {
          canvas.onmousemove = (e) => {
            ctx.clearRect(e.offsetX, e.offsetY, 10, 10);
          };

          canvas.onmouseup = () => {
            canvas.onmousemove = null;
          };
        }
      };
    </script>
  </body>
</html>
